// geometric_problem.cpp
// 04/15/2011: created

#include <fstream>
#include <cassert>
#include <QtGui>
#include "geometric_problem.h"
#include "Log.h"

QPointF Axis::point(double x, double y) {
  QSize size = m_widget->size();
  x = (x-m_xmin)/(m_xmax-m_xmin) * size.width();
  y = (m_ymax-y)/(m_ymax-m_ymin) * size.height();
  //Log::m_log << "w=" << size.width() << " h=" << size.height() << " x=" << x << " y=" << y << endl;
  return QPointF(x, y);
}

QPointF Axis::point(const vec& v) {
  assert(v.n_elem > 0);
  if (v.n_elem >= 2)
    return point(v[0], v[1]);
  else
    return point(v[0], 0);
}

QPointF Axis::distance(double x, double y)
{
  QSize size = m_widget->size();
  x = x/(m_xmax-m_xmin) * size.width();
  y = y/(m_ymax-m_ymin) * size.height();
  return QPointF(x,y);
}

QPointF Axis::reversePoint(const QPointF& p)
{
  QSize size = m_widget->size();
  double x = p.x(), y = p.y();
  x = m_xmin + x / size.width() * (m_xmax-m_xmin) ;
  y = m_ymax - y / size.height() * (m_ymax-m_ymin);
  return QPointF(x,y);
}

void PolygonMidpoint::loadData(const std::string& fName)
{
  m_vertex.clear();
  m_midpoint.clear();

  int n, d;
  std::ifstream is(fName.c_str());
  is >> n >> d;

  Log::m_log << "n=" << n << " d=" << d << endl;
  for (int i = 0; i < n && !is.eof(); i++) {
    m_vertex.push_back(vec(d));
    vec& v = m_vertex.back();
    v.load(is, arma::arma_ascii);
    assert(v.n_elem == d);
    //Log::m_log << "v[" << i << "]" << endl;
  }
  is.close();
}

void PolygonMidpoint::solve()
{
  m_midpoint.clear();
  int n = m_vertex.size();
  for (int i = 0; i < n; i++) {
    vec& p = m_vertex[i];
    vec& q = m_vertex[(i+1) % n];
    m_midpoint.push_back((p+q)/2);
  }
}

void PolygonMidpoint::draw(Plotter& pl)
{
  QPen pen(Qt::SolidLine);
  pen.setWidth(2);

  pen.setColor(Qt::black);
  pl.setPen(pen);
  int n = m_vertex.size();
  for (int i = 0; i < n; i++) {
    vec& p = m_vertex[i];
    vec& q = m_vertex[(i+1) % n];
    pl.drawLine(pl.point(p[0], p[1]), pl.point(q[0], q[1]));
  }

  pen.setColor(Qt::red);
  pl.setPen(pen);
  n = m_midpoint.size();
  for (int i = 0; i < n; i++) {
    vec& m = m_midpoint[i];
    pl.drawEllipse(pl.point(m[0], m[1]), 3.0, 3.0);
  }
}
